﻿using GodSystemBLL;
using GodSystemModel;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.OleDb;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace GodSystem.FormChildren
{
    public partial class FormProductAddBatch : Form
    {
        public FormProductAddBatch()
        {
            InitializeComponent();
        }

        private void button_TemplateDownload_Click(object sender, EventArgs e)
        {
            DownLoad();
        }


        private void DownLoad()
        {
            string startupPath = Application.StartupPath;
            startupPath = startupPath.Substring(0, startupPath.LastIndexOf("\\"));
            startupPath = startupPath.Substring(0, startupPath.LastIndexOf("\\"));
            string filePath = startupPath + "\\downloads\\产品批量导入模板.xlsx";
            string fileName = Path.GetFileName(filePath);
            SaveFileDialog saveFileDialog = new SaveFileDialog();
            saveFileDialog.Title = "文件下载";
            saveFileDialog.Filter = "xls文件(*.xls,*xlsx)|*.xls;*.xlsx;";
            // saveFileDialog.FileName = fileName;
            DialogResult dialogResult = saveFileDialog.ShowDialog(this);
    
            if (dialogResult == DialogResult.OK)
            {
                System.Net.WebClient client = new System.Net.WebClient();
                byte[] data = client.DownloadData(filePath);
                // 获取对话框中的全路径文件
                string newFilePath = saveFileDialog.FileName.ToString();
                FileStream fs = new FileStream(newFilePath, FileMode.Create);
                fs.Write(data,0, data.Length);
                fs.Close();
                MessageBox.Show("下载成功", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
            else
            {
                MessageBox.Show("下载失败","提示", MessageBoxButtons.OK,MessageBoxIcon.Error);
            }
        }

        private void button_ProductUpload_Click(object sender, EventArgs e)
        {
            string path = "";
            OpenFileDialog fd = new OpenFileDialog();
            fd.Title = "请选择要批量上传产品的表格";
            fd.Filter = "xls files(*.xls)|*.xls;*.xlsx;";
            if(fd.ShowDialog() == DialogResult.OK)
            {
                path = fd.FileName.Trim();
                path = path.Replace("\\", "/");
            }
            if (string.IsNullOrEmpty(path))
            {
                MessageBox.Show("请选择要上传的文件", "提示", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }

            string myString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + path + ";Extended Properties='Excel 8.0;HDR=No;IMEX=1;'";

            OleDbConnection cnnxls = new OleDbConnection(myString);
            OleDbDataAdapter myDa = new OleDbDataAdapter("Select * from [Sheet1$]", cnnxls);
            DataSet myDs = new DataSet();
            myDa.Fill(myDs);//数据存放在myDs中了

            int count = myDs.Tables[0].Rows.Count;
            if(count < 2)
            {
                MessageBox.Show("表格不能为空", "提示", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }
            try
            {
                string warningString = "";
                for(int i = 1; i < count; i++)
                {
                    int j = i + 1;
                    //获取每行每列的值
                    string productName = myDs.Tables[0].Rows[i].ItemArray[0].ToString();
                    string productSn = myDs.Tables[0].Rows[i].ItemArray[1].ToString();
                    string SupplierId = myDs.Tables[0].Rows[i].ItemArray[2].ToString();
                    string productStatus = myDs.Tables[0].Rows[i].ItemArray[3].ToString();
                    string cateIds = myDs.Tables[0].Rows[i].ItemArray[4].ToString();
                    string productMainSku = myDs.Tables[0].Rows[i].ItemArray[5].ToString();
                    string productWeight = myDs.Tables[0].Rows[i].ItemArray[6].ToString();
                    string productPrice = myDs.Tables[0].Rows[i].ItemArray[7].ToString();
                    string picPath = myDs.Tables[0].Rows[i].ItemArray[8].ToString();


                    ProductsBLL productsBLL = new ProductsBLL();

                    object num = productsBLL.CheckProductSn(productSn);
                    int total = Convert.ToInt32(num);
                    if (total > 0)
                    {
                        warningString += "第"+j.ToString()+",行此产品编号:"+ productSn + "已经存在，禁止重复导入\n\r";
                        continue;
                    }

                    ProductsModel product = new ProductsModel();
                    product.ProductName = productName.Trim();
                    product.ProductSn = productSn.Trim();
                    product.SupplierId = string.IsNullOrEmpty(SupplierId) ? 0 : Convert.ToInt32(SupplierId);
                    product.ProductStatus = Convert.ToInt32(productStatus);
                    product.CreateTime = DateTime.Now;
                    product.CateId = Convert.ToInt32(cateIds);
                    product.MainSku = productMainSku.Trim();
                    product.Weight = Convert.ToDecimal(productWeight);
                    product.PurchasePrice = Convert.ToDecimal(productPrice);
                    product.ProductThumbImage = picPath.Trim();
                    int result = productsBLL.AddProduct(product);
                    if (result == 0)
                    {
                    
                        string errorString = "从第"+j.ToString()+"行开始失败，请后面的重新导入";
                        MessageBox.Show("添加失败，请稍后再试", "提示", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        return;
                    }
                
                }
                if(warningString.Length > 0)
                {
                    MessageBox.Show(warningString, "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                }
                else
                {
                    MessageBox.Show("导入成功", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                }
            }catch(Exception ex)
            {
                MessageBox.Show("添加失败，请稍后再试," + ex.Message, "提示", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
    }
}
